import 'dart:io';
import 'package:logger/logger.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'file.dart';

class Log {
  static final Log _instance = Log._internal();
  factory Log() {
    return _instance;
  }
  Log._internal() {
    init();
  }

  late Logger log;

  // 初始化
  void init() {
    log = Logger(
        printer: PrettyPrinter(
      methodCount: 0, // 不打印调用方法名
      errorMethodCount: 5, // error 时打印 5 层调用方法名
      lineLength: 120, // 每行最长 120 字符
      printEmojis: true, // 启用表情符号
      colors: true, // 启用彩色打印
    ));
  }

  bool error(dynamic msg, {dynamic title = 'Error log'}) {
    try {
      log.e(title, error: msg.toString());
      output(msg, level: '  error');
      return true;
    } catch (e) {
      return false;
    }
  }

  bool warning(String msg) {
    try {
      log.w(msg.toString());
      output(msg, level: 'warning');
      return true;
    } catch (e) {
      return false;
    }
  }

  bool info(String msg) {
    try {
      log.i(msg.toString());
      return true;
    } catch (e) {
      return false;
    }
  }

  bool debug(String msg) {
    try {
      log.d(msg.toString());
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<void> output(String msg, {String level = 'info'}) async {
    try {
      var libFile = LibFile();
      var txt =
          '${DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now())} $level: $msg\n';
      var filepath = await libFile.getAppdir();
      filepath = "${filepath}log.log";

      print(filepath);
      await libFile.writeFile(filepath, "a", txt);

      // file.writeAsStringSync(
      //     ,
      //     mode: FileMode.append);
    } catch (e) {
      // ignore: avoid_print
      print('Error writing to log file: $e');
    }
  }
}
